package cn.itcast.ft.controller;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itcast.config.VisibleThreadPoolTaskExecutor;
import cn.itcast.ft.dto.*;
import cn.itcast.ft.entity.FTToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class WKJController {
    private static List<FTToken> tokenList=new ArrayList<>();
    @Autowired
    private VisibleThreadPoolTaskExecutor executor;
    @RequestMapping("/kjCreateMarket")
    public String wzhCreateMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                               @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                               @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        if(!CollectionUtils.isEmpty(tokenList)) {
            for (int i = 0; i < num; i++) {
                try {
                    for (int z = 0; z < tokenList.size(); z++) {
                        Proxy proxy = null;
                        confireMarketOrder(proxy, tokenList.get(z), goodsId, salePrice);
                        Thread.sleep(3000);
                    }
                } catch (Exception e) {
                    log.error("#####异常####" + e.getMessage());
                }
            }
            log.info("####FT执行完成#####");
        }
        return null;
    }
    public void confireMarketOrder(Proxy proxy,FTToken token,String goodsId,String salePrice){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice);
        }catch (Exception e){
            log.error("#####获取商品失败####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,FTToken token,String goodsId,String salePrice) throws InterruptedException {
        String response=null;
        WKJOrderDTO goodsDTO=null;
        try{
            JSONObject jsonObject=new JSONObject();
            jsonObject.putOnce("product_id",goodsId);
            response = HttpRequest.post("https://duoliang.cc/api/v2/nft/product/quickOrder")
                    .header("Authori-Zation",token.getToken())
                    .body(jsonObject.toString())
                    .execute().body();
            log.info("#####确认订单结果####"+response);
            goodsDTO= JSONUtil.toBean(response,WKJOrderDTO.class);
        }catch (Exception e){
            log.error("##获取商品数据异常###:"+e.getMessage()+"####返回数据：###"+response);
        }
        if(goodsDTO.getStatus()==200){
            Proxy finalProxy = proxy;
            WKJOrderDetailDTO detailDTO=goodsDTO.getData();
            executor.execute(()->{
                saveOrder(finalProxy,token,goodsId,detailDTO);
            });
            Thread.sleep(1000);
        }
    }
    public String addCardId(FTToken token,String goodsId,WKJOrderDetailDTO detailDTO){
        DLOrderDTO responseDTO=null;
        String response=null;
        try{
            JSONObject jsonObject=new JSONObject();
            jsonObject.putOnce("productId",goodsId);
            jsonObject.putOnce("cartNum",1);
            jsonObject.putOnce("uniqueId","");
            jsonObject.putOnce("new","1");
            jsonObject.putOnce("card_unique",detailDTO.getCard_unique());
            response = HttpRequest.post("https://duoliang.cc/api/cart/add")
                    .header("Authori-Zation",token.getToken())
                    .body(jsonObject.toString())
                    .execute().body();
            log.info("#####生成订单编号####"+response);
            responseDTO= JSONUtil.toBean(response,DLOrderDTO.class);
            if(responseDTO.getStatus()==200){
                return responseDTO.getData().getCartId();
            }
        }catch (Exception e){
            log.error("###生成订单编号失败###:"+e.getMessage()+",goodsId:"+goodsId+":"+detailDTO.toString()+"##返回的参数信息##:"+response+",#######:"+token);
        }
        return "";
    }
    public void saveOrder(Proxy proxy,FTToken token,String goodsId,WKJOrderDetailDTO detailDTO){
        DLConfirmOrderDTO responseDTO=null;
        String response=null;
        try{
            String cardId=addCardId(token,goodsId,detailDTO);
            JSONObject jsonObject=new JSONObject();
            jsonObject.putOnce("cartId",cardId);
            jsonObject.putOnce("card_unique",detailDTO.getCard_unique());
            jsonObject.putOnce("consign_unique",detailDTO.getConsign_unique());
            jsonObject.putOnce("card_no",detailDTO.getCard_no());
            jsonObject.putOnce("jump",0);
            response = HttpRequest.post("https://duoliang.cc/api/order/confirm")
                    .header("Authori-Zation",token.getToken())
                    .body(jsonObject.toString())
                    .execute().body();
            log.info("#####确认订单结果####"+response);
            responseDTO= JSONUtil.toBean(response,DLConfirmOrderDTO.class);
            if(responseDTO.getStatus()==200){
                addOrder(responseDTO.getData().getOrderKey(),detailDTO,token,goodsId,
                        responseDTO.getData().getPriceGroup().getTotalPrice());
            }
        }catch (Exception e){
            log.error("###确认订单失败###:"+e.getMessage()+",goodsId:"+goodsId+":"+detailDTO.toString()+"##返回的参数信息##:"+response+",#######:"+token);
        }

    }
    private void addOrder(String orderKey,WKJOrderDetailDTO detailDTO,FTToken token,String goodsId
            ,BigDecimal price) {
        DLOrderSaveDTO responseDTO=null;
        String response=null;
        try{
            JSONObject jsonObject=new JSONObject();
            jsonObject.putOnce("addressId",0);
            jsonObject.putOnce("couponId",0);
            jsonObject.putOnce("mark","");
            jsonObject.putOnce("payType","hf_pay");
            jsonObject.putOnce("quitUrl","https://duoliang.cc#/pages/order_pay_status/index?&type" +
                    "=3&totalPrice="+String.valueOf(price));
            response = HttpRequest.post("https://duoliang.cc/api/order/create/"+orderKey)
                    .header("Authori-Zation",token.getToken())
                    .body(jsonObject.toString())
                    .execute().body();
            log.info("#####生成订单编号####"+response);
            responseDTO= JSONUtil.toBean(response,DLOrderSaveDTO.class);
            if(responseDTO.getStatus()==200){
                MailUtil.send("1027060531@qq.com", "收到订单", "您有一个订单:"+token.getRefreshToken()+"，请赶紧支付！", false);
            }
        }catch (Exception e){
            log.error("###生成订单编号失败###:"+e.getMessage()+",goodsId:"+goodsId+":"+detailDTO.toString()+"##返回的参数信息##:"+response+",#######:"+token);
        }

    }
    @RequestMapping("/kj_addUser")
    public String wzhCreateMarket(
            @RequestParam(value = "account") String account,
            @RequestParam(value = "wx") String wx,
            @RequestParam(value = "password") String password) {
        String response=null;
        WKUserDTO goodsDTO=null;
        try{
            JSONObject jsonObject=new JSONObject();
            jsonObject.putOnce("account",account);
            jsonObject.putOnce("password",password);
            response = HttpRequest.post("https://duoliang.cc/api/login")
                    .body(jsonObject.toString())
                    .execute().body();
            log.info("#####确认订单结果####"+response);
            goodsDTO= JSONUtil.toBean(response,WKUserDTO.class);
        }catch (Exception e){
            log.error("##获取商品数据异常###:"+e.getMessage()+"####返回数据：###"+response);
        }
        if(goodsDTO.getStatus()==200){
            FTToken token4=new FTToken();
            String token="Bearer "+goodsDTO.getData().getToken();
            token4.setToken(token);
            token4.setRefreshToken("微信名字:"+wx);
            tokenList.add(token4);
        }else{
            log.error("##账号密码错###:"+wx);
        }
        return null;
    }
}
